package cn.vic.db.sql;

import cn.vic.config.model.DatabaseElement;
import cn.vic.exception.ApplicationException;
import cn.vic.model.TableUpdateModel;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by vic on 2017/8/25.
 */
public class MysqlSqlFormat extends BaseSqlFormat implements BaseSqlInterface {
    private DatabaseElement databaseElement;

    public MysqlSqlFormat(DatabaseElement databaseElement) {
        this.databaseElement = databaseElement;
    }

    @Override
    public String getUpdateRemarksSql(TableUpdateModel updateModel) {
        String sqlStr = "ALTER TABLE `%s` MODIFY COLUMN `%s`  %s DEFAULT NULL COMMENT '%s';";
        //String type = findType(updateModel);
        String type = updateModel.getType();
        return String.format(sqlStr, updateModel.getTableName(), updateModel.getColumnName(), type, updateModel.getColumnValue());
    }

    /**
     * 查询type
     *
     * @param updateModel
     * @return
     */
    private String findType(TableUpdateModel updateModel) {
        StringBuffer sql = new StringBuffer("select COLUMN_TYPE from INFORMATION_SCHEMA.Columns ");
        sql.append(" where table_schema=").append("'").append(updateModel.getLibName()).append("'");
        sql.append(" and table_name=").append("'").append(updateModel.getTableName()).append("'");
        sql.append(" and COLUMN_NAME=").append("'").append(updateModel.getColumnName()).append("'");
        //切记左边菜单  鼠标不要移出到别的库
        try {
            List<String> stringList = findDbList(databaseElement.getConnection(), sql.toString());
            if (stringList.size() > 0) {
                updateModel.setType(stringList.get(0));
            }
        } catch (SQLException e1) {
            e1.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ApplicationException e) {
            e.printStackTrace();
        }
        return updateModel.getType();
    }

}
